package a66weding.com.jiehuntong.activity.toolsseat;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.List;

import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.application.GlobalApplication;
import a66weding.com.jiehuntong.beans.CommonResultBean;
import a66weding.com.jiehuntong.beans.ErrorBean;
import a66weding.com.jiehuntong.beans.HttpRequestBean;
import a66weding.com.jiehuntong.beans.SeatBean;
import a66weding.com.jiehuntong.beans.SuccessBean;
import a66weding.com.jiehuntong.common.CommonAdapter;
import a66weding.com.jiehuntong.common.MessageEvent;
import a66weding.com.jiehuntong.common.MyViewHolder;
import a66weding.com.jiehuntong.common.utils.CUtils;
import a66weding.com.jiehuntong.common.utils.ChineseUpperCaser;
import a66weding.com.jiehuntong.http.HttpHandleUtil;
import a66weding.com.jiehuntong.http.NetStatusUtil;
import a66weding.com.jiehuntong.http.OnNetResultListener;
import a66weding.com.jiehuntong.http.RequestCode;
import a66weding.com.jiehuntong.http.UrlDealUtil;
import a66weding.com.jiehuntong.view.ConfirmDialog;
import me.imid.swipebacklayout.lib.SwipeBackLayout;
import me.imid.swipebacklayout.lib.app.SwipeBackActivity;

public class ToolsSeatAddSeatActivity extends SeatBaseActivity implements View.OnClickListener, OnNetResultListener, TextWatcher {
    private View myBodyView;
    private TextView mHeadAddSeatTv;
    private Button mAddSeatBtn;
    private LinearLayout mBackLay;
    private RelativeLayout mProgressLay;
    private LinearLayout mEmptySeatLay;
    private ListView mSeatListView;
    private LinearLayout mContentLay;
    private RelativeLayout mContentRlay;
    private ImageView mNoNetIv;
    private LinearLayout mNoNetLay;
    private EditText mSearchSeatEt;
    private LinearLayout mClickLay;
    private TextView mEditItemTv;

    private SwipeBackLayout mSwipeBackLayout;
    private List<SeatBean.DataBean> seatList;
    private CommonAdapter mSeatAdapter;
    private int mCurrentPosition;

    public static final int EDITSEAT=5;
    private SeatBean.DataBean mCurrentdataBean;
    private String searchString;
    private boolean isSearch;
    private SeatBean seatdata;
    private SeatBean searchData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tools_seat_add_seat);
        ((GlobalApplication) getApplication()).getActivityManager().addActivity("ToolsSeatAddSeatActivity", this);
        mSwipeBackLayout=getSwipeBackLayout();
        mSwipeBackLayout.setEdgeTrackingEnabled(SwipeBackLayout.EDGE_LEFT);

        initview();

        initdata();
    }

    private void initview() {

        mAddSeatBtn = (Button) findViewById(R.id.btn_tools_seat_addseat);
        mHeadAddSeatTv = (TextView) findViewById(R.id.tv_tools_seat_addseat);
        mBackLay = (LinearLayout) findViewById(R.id.llay_toolseat_back);
        mProgressLay = (RelativeLayout) findViewById(R.id.progressbar);
        mEmptySeatLay = (LinearLayout) findViewById(R.id.llay_tools_seat_emptyseat);
        mSeatListView = (ListView) findViewById(R.id.lview_tools_seatlist);
        mContentLay = (LinearLayout) findViewById(R.id.llay_tools_seat_content);
        mContentRlay = (RelativeLayout) findViewById(R.id.rlay_content);
        mNoNetLay = (LinearLayout) findViewById(R.id.llay_nonetwork);
        mSearchSeatEt = (EditText) findViewById(R.id.et_searchseat);



        mProgressLay.setVisibility(View.VISIBLE);
        mContentLay.setVisibility(View.GONE);
        mEmptySeatLay.setVisibility(View.GONE);


        mHeadAddSeatTv.setOnClickListener(this);
        mAddSeatBtn.setOnClickListener(this);
        mBackLay.setOnClickListener(this);

        mSearchSeatEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                return (event.getKeyCode() == KeyEvent.KEYCODE_ENTER);
            }
        });
        mSearchSeatEt.addTextChangedListener(this);


    }

//    @Override
    protected void initdata() {

        String url= UrlDealUtil.getRealUrl(RequestCode.RETURN_WEDDINGTABLE);

        HttpRequestBean seathttp = new HttpRequestBean(RequestCode.POSTEQUEST,url,this,
                SeatBean.class,RequestCode.RETURN_WEDDINGTABLE);

        HttpHandleUtil.executeCommonPost(this,seathttp);
    }


    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.tv_tools_seat_addseat:


            case R.id.btn_tools_seat_addseat://添加座位

                Intent intent = new Intent(this, ToolsSeatAddSeatInfoActivity.class);
                if(seatList!=null) {
                    intent.putExtra("tablecount",seatList.size());
                }else{
                    intent.putExtra("tablecount",0);
                }
                startActivityForResult(intent,EDITSEAT);
                break;
            case R.id.tv_tools_seat_delitem:
                mCurrentPosition = (int) view.getTag();
                mCurrentdataBean = seatList.get(mCurrentPosition);

                showDialog(this, "您确定删除本桌？", "确定", "取消");


                break;
            case R.id.iv_nonet:
                String url= UrlDealUtil.getRealUrl(RequestCode.RETURN_WEDDINGTABLE);

                HttpRequestBean seathttp = new HttpRequestBean(RequestCode.POSTEQUEST,url,this,
                        SeatBean.class,RequestCode.RETURN_WEDDINGTABLE);
                HttpHandleUtil.executeCommonPost(this,seathttp);



                break;
            case R.id.llay_clickContent:
                mCurrentPosition = (int) view.getTag();
                SeatBean.DataBean dataBean2 = seatList.get(mCurrentPosition);
                super.setmSeatbean(dataBean2);
                Intent intent2 = new Intent(this, ToolsSeatAddSeatInfoActivity.class);
                Bundle bundle=new Bundle();
                bundle.putSerializable("seatbean",dataBean2);
                intent2.putExtra("position",mCurrentPosition);
                intent2.putExtra("isedit",true);
                intent2.putExtras(bundle);
                startActivityForResult(intent2,EDITSEAT);


                break;
            case R.id.llay_toolseat_back:
                finish();
                break;
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==EDITSEAT) {
            if(data!=null) {
                String result = data.getStringExtra("result");
                if("sucess".equals(result)) {
                    String url= UrlDealUtil.getRealUrl(RequestCode.RETURN_WEDDINGTABLE);
                    HttpRequestBean seathttp = new HttpRequestBean(RequestCode.POSTEQUEST,url,this,
                            SeatBean.class,RequestCode.RETURN_WEDDINGTABLE);
                    HttpHandleUtil.executeCommonPost(this,seathttp);
                }
            }

        }
    }


    @Override
    public void onSucess(SuccessBean sucessbean) {
        mNoNetLay.setVisibility(View.GONE);

        Object data = sucessbean.getData();

        if(data instanceof CommonResultBean) {
            CommonResultBean commondata= (CommonResultBean) data;
            switch (commondata.getResCode()) {
                    case "0000":
                        seatList.remove(mCurrentPosition);
                        if(mSeatAdapter!=null) {
                            mSeatAdapter.notifyDataSetChanged();
                        }
                        if(seatList.size()<1) {
                            mContentLay.setVisibility(View.GONE);
                            mEmptySeatLay.setVisibility(View.VISIBLE);
                            return;
                        }

                    break;
                     case "0001":

                    break;
                     case "0002":

                    break;
                     case "0003":

                    break;
            }


        }else if(data instanceof SeatBean){
            if(isSearch) {
                searchData = (SeatBean) data;
            }else{
                seatdata = (SeatBean) data;
            }

            mContentLay.setVisibility(View.VISIBLE);
            switch (seatdata.getResCode()) {
                    case "0000":
                        notifyViewLay(HAVEDATA);
                        if(isSearch) {
                            setAdapter(searchData);
                        }else{
                            setAdapter(seatdata);
                        }
                    break;
                     case "0001":

                    break;
                     case "0002":

                    break;
                     case "0003":
                         if(isSearch) {
                             notifyViewLay(HAVEDATA);
                             setAdapter(seatdata);
                         }else{
                             mEmptySeatLay.setVisibility(View.VISIBLE);
                             mContentLay.setVisibility(View.GONE);
                         }


                    break;
            }
        }

        mProgressLay.setVisibility(View.GONE);


    }



    @Override
    public void onError(ErrorBean errorBean) {
        int errorCode = errorBean.getErrorCode();
        mProgressLay.setVisibility(View.GONE);
        switch (errorCode) {
                case ErrorBean.NONET:
//                    loadNoNetWorkView(this,mContentRlay);
                    mNoNetLay.setVisibility(View.VISIBLE);
                    mNoNetIv = (ImageView) findViewById(R.id.iv_nonet);
                    mNoNetIv.setOnClickListener(this);

                break;
                default:
                    CUtils.showDataErrToast(this);

        }

    }


    public  void showDialog(Context context, String title, String confirm, String cancel) {
        final ConfirmDialog confirmDialog = new ConfirmDialog(context, title, confirm, cancel,R.layout.confirm_dialog);
        confirmDialog.show();
        confirmDialog.setClicklistener(new ConfirmDialog.ClickListenerInterface() {
            @Override
            public void doConfirm() {
                String delurl= UrlDealUtil.getRealUrl(RequestCode.DELECT_TABLEINFO);
                HashMap<String, String> delMap = new HashMap<>();
                delMap.put("TableName",mCurrentdataBean.getTableName());
                delMap.put("WeddingTableID",""+mCurrentdataBean.getWeddingTableID());
                delMap.put("CustomerName",mCurrentdataBean.getCustomerName());
                delMap.put("PeopleNumber",String.valueOf(mCurrentdataBean.getPeopleNumber()));

                HttpRequestBean delhttp = new HttpRequestBean(RequestCode.POSTEQUEST,delurl,ToolsSeatAddSeatActivity.this,
                        CommonResultBean.class,RequestCode.DELECT_TABLEINFO,delMap);
                HttpHandleUtil.executeCommonPost(ToolsSeatAddSeatActivity.this,delhttp);
                confirmDialog.dismiss();


            }

            @Override
            public void doCancel() {
                confirmDialog.dismiss();
            }
        });
    }


    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        isSearch=true;
        searchString = s.toString().trim();

        if(TextUtils.isEmpty(searchString)) {
            setAdapter(seatdata);
        }else{
            searchInfo(searchString);
        }


    }

    private void setAdapter(SeatBean seatdata){

        seatList = seatdata.getData();
        if(seatList!=null ) {
            mSeatAdapter=new CommonAdapter<SeatBean.DataBean>(this,seatList,R.layout.item_tools_seat_contentitem) {
                @Override
                public void convert(MyViewHolder holder, int position) {
                    SeatBean.DataBean tableinfo = seatList.get(position);
                    int peopleNumber = tableinfo.getPeopleNumber();
                    String seatInfo="第"+ChineseUpperCaser.paseIntegerToStr(position+1)+"桌"+" ("+tableinfo.getPeopleNumber()+"人)";
                    holder.setText(R.id.item_deskNum, seatInfo);
                    holder.setText(R.id.item_tabName,tableinfo.getTableName());
                    holder.setText(R.id.item_tabMessage,tableinfo.getCustomerName());
                    TextView delTv = (TextView) holder.getView(R.id.tv_tools_seat_delitem);
                    TextView editTv = (TextView) holder.getView(R.id.tv_tools_seat_edititem);
                    editTv.setVisibility(View.GONE);
                    LinearLayout clickLay= (LinearLayout) holder.getView(R.id.llay_clickContent);


                    delTv.setTag(position);
                    delTv.setOnClickListener(ToolsSeatAddSeatActivity.this);

                    clickLay.setTag(position);
                    clickLay.setOnClickListener(ToolsSeatAddSeatActivity.this);
                }
            };
            mSeatListView.setAdapter(mSeatAdapter);
        }

    }

    private void searchInfo(String searchString) {

        String url=UrlDealUtil.getRealUrl(RequestCode.SELECT_WEDDINGTABLE);

        HashMap<String,String> searchMap=new HashMap<String,String>();
        searchMap.put("CustomerName",searchString);

        HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.POSTEQUEST, url, this, SeatBean.class, RequestCode.SELECT_WEDDINGTABLE, searchMap);

        HttpHandleUtil.executeCommonPost(this,httpRequestBean);
    }


    private void notifyViewLay(int state){
        switch (state) {
            case HAVEDATA:
                mEmptySeatLay.setVisibility(View.GONE);
                break;
            case NODATA:
                mEmptySeatLay.setVisibility(View.VISIBLE);
                break;
            case DATAERROR:

                break;
        }
    }

}
